//
//  WJQUserRegisterViewController.m
//  TripTogether
//
//  Created by inremembert on 16/1/2.
//  Copyright © 2016年 杨泓晔. All rights reserved.
//

#import "WJQUserRegisterViewController.h"
#import "WJQUserInfoViewController.h"
#import "WJQUserInfoModel.h"

@interface WJQUserRegisterViewController ()

@property (nonatomic, strong) UITextField *phoneTextF;
@property (nonatomic, strong) UITextField *codeTextF;
@property (nonatomic, strong) UIButton *codeButton;
@property (nonatomic, strong) UITextField *passTextF;

@property (nonatomic, strong) UIButton *registerButton;

@property (nonatomic, strong) NSMutableDictionary *userInfoDic;

@end

@implementation WJQUserRegisterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    _userInfoDic = [NSMutableDictionary dictionary];
    
    
    
    [self createBackButton];
    
    [self createSubViews];
    
    // 刷新用户首页

      [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(closeView) name:@"close" object:nil];
}
- (void)closeView
{
    [self dismissViewControllerAnimated:NO completion:^{
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"loginClose" object:nil];
    }];
    
   
}
- (void)createSubViews
{
    self.view.backgroundColor = [UIColor colorWithRed:0.320 green:0.740 blue:0.800 alpha:1.000];
    
    
    UILabel *zoneL = [UILabel new];
//    zoneL.backgroundColor = [UIColor orangeColor];
    zoneL.text = @"+86";
    zoneL.textAlignment = NSTextAlignmentCenter;
    zoneL.textColor = [UIColor whiteColor];
    [self.view addSubview:zoneL];
    
    [zoneL mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.size.mas_equalTo(CGSizeMake(50, 30));
        make.top.mas_equalTo(150 * AUTO_HEIGHT);
        make.left.mas_equalTo(30 * AUTO_WIDTH);
    }];
    
    _phoneTextF = [UITextField new];
    _phoneTextF.backgroundColor = [UIColor colorWithRed:0.320 green:0.740 blue:0.800 alpha:1.000];
//    _phoneTextF.borderStyle = UITextBorderStyleBezel;
    _phoneTextF.placeholder = @"请输入手机号码";
    _phoneTextF.font = [UIFont fontWithName:@"Lao Sangam MN" size:16];
    _phoneTextF.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
    [self.view addSubview:_phoneTextF];
    _phoneTextF.textColor = [UIColor whiteColor];

    [_phoneTextF mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.mas_equalTo(zoneL);
        make.left.mas_equalTo(zoneL.mas_right).offset(20 * AUTO_WIDTH);
        make.right.mas_equalTo(-20 * AUTO_WIDTH);
        make.height.mas_equalTo(zoneL);
    }];
    
    /* 改变placeholder的颜色 */
    [_phoneTextF setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];
    
 
    
    UIView *lin = [UIView new];
    lin.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:lin];
    
    [lin mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.view).offset(20 * AUTO_WIDTH);
        make.top.mas_equalTo(_phoneTextF.mas_bottom).offset(15 * AUTO_HEIGHT);
        make.right.mas_equalTo(self.view).offset(- 20 * AUTO_WIDTH);
        make.height.mas_equalTo(@1);
        
    }];
    
    
    
    
    
    
    
    _codeButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _codeButton.backgroundColor = [UIColor whiteColor];
    [_codeButton setTitle:@"获取验证码" forState:UIControlStateNormal];
    [_codeButton setTitleColor:self.view.backgroundColor forState:UIControlStateNormal];
    _codeButton.titleLabel.font = [UIFont systemFontOfSize:13.f];
    _codeButton.layer.cornerRadius = 12.f;
    
    [_codeButton addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_codeButton];
    
    
    
    
    
    _codeTextF = [UITextField new];
    // _codeTextF.borderStyle = UITextBorderStyleRoundedRect;
    _codeTextF.placeholder = @"短信验证码";
    [_codeTextF setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];
    _codeTextF.font = [UIFont fontWithName:@"Lao Sangam MN" size:16];
    _codeTextF.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
    [self.view addSubview:_codeTextF];
    
    
    
    [_codeButton mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.size.mas_equalTo(CGSizeMake(80, 26));
        make.right.mas_equalTo(_phoneTextF);
        make.top.mas_equalTo(lin.mas_top).offset(20 * AUTO_HEIGHT);
        
    }];
    _codeTextF.textColor = [UIColor whiteColor];

    [_codeTextF mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.mas_equalTo(lin.mas_bottom).offset(20 * AUTO_HEIGHT);
        make.left.mas_equalTo(zoneL.mas_left);
        make.right.mas_equalTo(_codeButton.mas_left).offset(-20 * AUTO_WIDTH) ;
        make.height.mas_equalTo(_phoneTextF.mas_height);
        
        
    }];
    
    
    
    UIView *viewlin = [UIView new];
    viewlin.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:viewlin];
    [viewlin mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_codeTextF.mas_bottom).offset(15 * AUTO_HEIGHT);
        make.left.mas_equalTo(self.view).offset(20  *AUTO_WIDTH);
        make.right.mas_equalTo(self.view).offset(- 20 * AUTO_WIDTH);
        make.height.mas_equalTo(@1);
    }];
    
    
    
    
    
    
    
    
    
    _passTextF = [UITextField new];
    
  //  _passTextF.borderStyle = UITextBorderStyleRoundedRect;
    _passTextF.placeholder = @"输入登陆密码，至少6位";
    _passTextF.secureTextEntry = YES;
    [self.view addSubview:_passTextF];
    [_passTextF setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];
    _passTextF.font = [UIFont fontWithName:@"Lao Sangam MN" size:16];
     _passTextF.textColor = [UIColor whiteColor];
    
    [_passTextF mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.mas_equalTo(_codeTextF.mas_bottom).offset(30 * AUTO_HEIGHT);
        make.height.mas_equalTo(_codeTextF);
        make.right.mas_equalTo(_codeButton.mas_right);
        make.left.mas_equalTo(_codeTextF);
        
    }];
    
    
    
    UIView *viewl = [UIView new];
    viewl.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:viewl];
    [viewl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_passTextF.mas_bottom).offset(15 *AUTO_HEIGHT);
        make.left.mas_equalTo(self.view).offset(20 *AUTO_WIDTH);
        make.right.mas_equalTo(self.view).offset(- 20 * AUTO_WIDTH);
        make.height.mas_equalTo(@1);

        
    }];
    
    


    _registerButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _registerButton.backgroundColor = [UIColor clearColor];
    [_registerButton setTitle:@"同意协议并注册" forState:UIControlStateNormal];
    [_registerButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    _registerButton.layer.borderWidth = 1.5f;
    _registerButton.layer.borderColor = [UIColor whiteColor].CGColor;
    _registerButton.layer.cornerRadius = 21.f;
    [_registerButton addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_registerButton];
    
    [_registerButton mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.size.mas_equalTo(CGSizeMake(200, 40));
        make.centerX.mas_equalTo(@0);
        make.top.mas_equalTo(_passTextF.mas_bottom).offset(100 * AUTO_HEIGHT);
        
        
    }];
    
//    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
//    button.frame = CGRectMake(100, 50, 80, 30);
//    button.backgroundColor = [UIColor orangeColor];
//    [button addTarget:self action:@selector(iibuttonAction) forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:button];
    
    
    
    
    UIView *linn = [UIView new];
    linn.backgroundColor = [UIColor colorWithRed:0.960 green:0.914 blue:1.000 alpha:1.000];
    [self.view addSubview:linn];
    
    [linn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.view);
        make.top.mas_equalTo(self.view.mas_bottom).offset(-60 * AUTO_HEIGHT);
        make.width.mas_equalTo(self.view);
        make.height.mas_equalTo(1);
        
    }];
    
    
    
    UIButton *la = [UIButton buttonWithType:UIButtonTypeCustom];
    //la.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:la];
    [la setTitle:@"已有账号登入" forState:UIControlStateNormal];
    la.titleLabel.textColor = [UIColor colorWithRed:0.980 green:0.961 blue:0.910 alpha:1.000];
    la.titleLabel.font = [UIFont systemFontOfSize:16.f];
    [la addTarget:self action:@selector(laAction) forControlEvents:UIControlEventTouchUpInside];
    [la mas_makeConstraints:^(MASConstraintMaker *make) {
        
    
        make.centerX.mas_equalTo(@0);
        make.top.mas_equalTo(linn.mas_bottom).offset(0);
        make.width.mas_equalTo(self.view);
        make.height.mas_equalTo(60 * AUTO_HEIGHT);
    }];
    
    
    
    
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction)];
    [self.view addGestureRecognizer:tap];

}
- (void)tapAction
{
    if ([_codeTextF isFirstResponder]) {
        [_codeTextF resignFirstResponder];
    }
    if ([_passTextF isFirstResponder]) {
        [_passTextF resignFirstResponder];
    }
    if ([_phoneTextF isFirstResponder]) {
        [_phoneTextF resignFirstResponder];
    }
}
- (void)laAction
{
    [self dismissViewControllerAnimated:YES completion:^{
        
        
    }];
}
//- (void)iibuttonAction
//{
//    WJQUserInfoViewController *vc = [[WJQUserInfoViewController alloc] init];
//    
//    UINavigationController *nc = [[UINavigationController alloc] initWithRootViewController:vc];
// 
//    
//    [self presentViewController:nc animated:YES completion:^{
//        
//        
//    }];
//}
- (void)buttonAction:(UIButton *)sender
{
    if (_codeButton == sender) {
        
        if ([self checkTel:_phoneTextF.text]) {
            // 手机格式验证成功
            
            _codeButton.userInteractionEnabled = NO;
            [_codeButton setTitle:@"正在获取中" forState:UIControlStateNormal];
            
            // 查找用户
            BmobQuery *query = [BmobUser query];
            [query whereKey:@"mobilePhoneNumber" equalTo:_phoneTextF.text];
            
            [query findObjectsInBackgroundWithBlock:^(NSArray *array, NSError *error) {
                
                if (array.count > 0) {
                    // 手机已经注册过了
                    [self alertControllerWithTitle:@"提示" message:@"该手机已注册"];
                    
                    _codeButton.userInteractionEnabled = YES;
                    [_codeButton setTitle:@"获取验证码" forState:UIControlStateNormal];
                    
                    return;
                } else {
                    
                    [self getcode];
                }
                for (BmobUser *user in array) {
                    NSLog(@"objectid %@",user.username);
                }
            }];
            
            
            
        }
        
    } else if (_registerButton == sender) {
        // 点击注册按钮
        
        if (0 == _codeTextF.text.length || 0 == _passTextF.text.length) {

            [self alertControllerWithTitle:@"提示" message:@"验证码或密码不能为空"];

        } else {
            
            // 密码验证通过
            if ([self checkPassword:_passTextF.text]) {
                
                [self MBShow];
                
                
                [SMSSDK commitVerificationCode:_codeTextF.text phoneNumber:_phoneTextF.text zone:@"86" result:^(NSError *error) {
                    
                    
                    
                    if (!error) {
                        // 验证码填写正确
                        
                        // 暂存用户信息
                        [_userInfoDic removeAllObjects];
                        
                        
//                        // 上传用户头像
//                        NSBundle    *bundle = [NSBundle mainBundle];
//                        NSString *fileString = [NSString stringWithFormat:@"%@/user_info_following_button_image@2x~ipad.png" ,[bundle bundlePath]];
//                        BmobObject *obj = [[BmobObject alloc] initWithClassName:@"UserHeadImage"];
//                        BmobFile *file1 = [[BmobFile alloc] initWithFilePath:fileString];
//                        [file1 saveInBackground:^(BOOL isSuccessful, NSError *error) {
//                            //如果文件保存成功，则把文件添加到filetype列
//                            if (isSuccessful) {
//                                
////                                [obj setObject:file1  forKey:@"filetype"];
////                                [obj saveInBackground];
//                                //打印file文件的url地址
//                                NSLog(@"file1 url %@",file1.url);
//                                
//                            }else{
//                                //进行处理
//                            }
//                        }];
                        
                        BmobUser *bUser = [[BmobUser alloc] init];
                        [bUser setUsername:_phoneTextF.text];
                        [bUser setPassword:_passTextF.text];
                        [bUser setObject:_phoneTextF.text forKey:@"mobilePhoneNumber"];
                        [bUser setObject:[NSNumber numberWithBool:YES] forKey:@"mobilePhoneNumberVerified"];
                        [bUser setObject:@"http://file.bmob.cn/M02/34/FA/oYYBAFaJwpyATgp8AAAGcs1pjPg903.png" forKey:@"imageurl"];
                        
                        [bUser signUpInBackgroundWithBlock:^ (BOOL isSuccessful, NSError *error){
                            
                            [self MBHide];
                            
                            if (isSuccessful){
                                
                                
                                WJQUserInfoModel *infoMod = [WJQUserInfoModel new];
                                infoMod.userName = _phoneTextF.text;
                                infoMod.phone = _phoneTextF.text;
                                infoMod.imageURL = @"http://file.bmob.cn/M02/34/FA/oYYBAFaJwpyATgp8AAAGcs1pjPg903.png";

                                // 注册成功
                                NSLog(@"注册成功");
                                
                                WJQUserInfoViewController *vc = [[WJQUserInfoViewController alloc] init];
                                vc.infoMod = infoMod;
                                UINavigationController *nc = [[UINavigationController alloc] initWithRootViewController:vc];
                                
                                [self presentViewController:nc animated:YES completion:^{
                                    
                                    
                                }];

                                
                            } else {
                                
                                // 注册失败
                                [self alertError:error];

                            }
                        }];
                        
                        
                    }
                    else
                    {
                        [self MBHide];
                        [self alertControllerWithTitle:@"提示" message:@"验证码错误请重新输入"];
                        NSLog(@"错误信息:%@",error);
                    }
                }];

                
            } else {
                [self alertControllerWithTitle:@"密码格式不对 请重新输入" message:@"密码只能给你包含数字和字母, 至少6位最长20位"];
            }
        }
    }
}
-(void)getcode
{
    [SMSSDK getVerificationCodeByMethod:SMSGetCodeMethodSMS phoneNumber:_phoneTextF.text zone:@"86" customIdentifier:nil result:^(NSError *error) {
        
        if (!error) {
            
            NSLog(@"获取验证码成功");
            [self startTime];
        } else {
           
            [self alertError:error];
        }
    }];

}
// 错误提示
- (void)alertError:(NSError *)error
{
    // 验证码获取失败
    NSDictionary *errorDic = error.userInfo;
    [self alertControllerWithTitle:@"错误" message:[errorDic objectForKey:@"getVerificationCode"]];
    
    _codeButton.userInteractionEnabled = YES;
    [_codeButton setTitle:@"获取验证码" forState:UIControlStateNormal];
}
-(void)startTime
{
    
    __block int timeout = 30; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        
        if(timeout <= 0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示
                [_codeButton setTitle:@"获取验证码" forState:UIControlStateNormal];
                _codeButton.userInteractionEnabled = YES;
            });
        }else{
            int seconds = timeout % 60;
            NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示
                //NSLog(@"____%@",strTime);
                [UIView beginAnimations:nil context:nil];
                [UIView setAnimationDuration:1];
                [_codeButton setTitle:[NSString stringWithFormat:@"%@秒后重发",strTime] forState:UIControlStateNormal];
                [UIView commitAnimations];
                _codeButton.userInteractionEnabled = NO;
            });
            timeout--;
        }
    });
    dispatch_resume(_timer);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
